package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.feign.UserInfoFeignApi;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieRefreshFilter extends ZuulFilter {
    @Autowired
    private UserInfoFeignApi userInfoFeignApi;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //判断请求中是否携带Cookie
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        String token = CookieUtil.getCookieValue(request, "userToken");

        if (!StringUtils.isEmpty(token)) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();

        String token = CookieUtil.getCookieValue(request, "userToken");
        //延迟redis的缓存数据,在会员服务操作
        //远程调用服务
        Result<Boolean> result = userInfoFeignApi.refreshRedisToken(token);

        if (result != null && result.getCode() == 200 && result.getData()) {

            //延长Cookie的时间
            Cookie userToken = CookieUtil.getCookie(request, "userToken");

            CookieUtil.addCookei("userToken", token, 1800, response);
        }
        currentContext.setSendZuulResponse(false);

        return null;
    }
}
